package com.chromatic.competition.view.notifications;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chromatic.competition.R;
import com.chromatic.competition.adapter.MessagesAdapter;
import com.chromatic.competition.inteface.ChatHistoryCallback;
import com.chromatic.competition.model.UserMessage;
import com.chromatic.competition.service.MessagesDatabaseService;
import com.chromatic.competition.utils.TimestampUtil;
import com.chromatic.competition.utils.UserLoginStatus;
import com.chromatic.competition.utils.UserManager;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class ChatActivity extends AppCompatActivity implements ChatHistoryCallback{
    private TextView friendName;
    private RecyclerView recyclerView;
    private MessagesAdapter messagesAdapter;
    private SwipeRefreshLayout swipeRefreshLayout;
    private EditText messageEditText;
    private final UserManager manager = new UserManager();
    private Timer timer;
//    private final boolean isFirstLoad = true;
    private int friendId;
    private int currentUserId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 获取传递过来的自己的ID好友ID
        Intent intent = getIntent();
        friendId = intent.getIntExtra("friend_id", 0);
        currentUserId = new UserLoginStatus(this).getCurrentUserId();

        // 初始化 RecyclerView
        setContentView(R.layout.activity_chat);
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        friendName = findViewById(R.id.title_friendname);
        getFriendNickname(friendId);

        // 加载聊天记录
        messagesAdapter = new MessagesAdapter(currentUserId, friendId);
        recyclerView.setAdapter(messagesAdapter);

        // 初始化 SwipeRefreshLayout
        swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setOnRefreshListener(() -> loadChatHistory(friendId));

        // 初始化 EditText
        messageEditText = findViewById(R.id.messageEditText);

        // 设置发送按钮的点击监听器
        Button sendButton = findViewById(R.id.sendButton);
        sendButton.setOnClickListener(v -> {
            String messageText = messageEditText.getText().toString();
            if (!messageText.isEmpty()) {
                sendMessage(messageText, currentUserId, friendId);
                messageEditText.setText("");
//                SocketClient client = new SocketClient("10.0.2.2", 5050);
//                client.sendMessage(messageText);
                displayNewMessage(messageText); // 显示消息
            }
        });
        loadChatHistory(friendId);

        ImageView backButton = findViewById(R.id.backButton);
        backButton.setOnClickListener(v -> onBackPressed());

//        scrollToLastMessage();

        // 创建定时器并定义计时器任务
        timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                loadChatHistory(friendId);
            }
        };

        // 启动定时器
        // 设置计时器任务的执行间隔为 1.0 秒（1000 毫秒）
        long delay = 0;
        long interval = 1000;
        timer.scheduleAtFixedRate(timerTask, delay, interval);
    }
    private void getFriendNickname(int friendUserId) {
        manager.getUserNickname(friendUserId, new UserManager.UserNicknameCallback() {
            @Override
            public void onSuccess(String nickname) {
                // 处理成功获取到的好友昵称
                updateNickname(nickname);
            }
            @Override
            public void onError(String errorMessage) {
                // 处理错误情况
                Log.e("调用getUserNickname方法", "获取好友昵称失败：" + errorMessage);
                Toast.makeText(ChatActivity.this, "Error getting friend nickname: " + errorMessage, Toast.LENGTH_LONG).show();
            }
        });
    }
    private void updateNickname(String nickname) {
        friendName.setText(nickname);
        Log.d("调用getUserNickname方法", "获取到的好友昵称：" + nickname);
    }

    private void loadChatHistory(int friendId) {
        // 创建 MessagesService 实例
        MessagesDatabaseService messagesDatabaseService = new MessagesDatabaseService();
        messagesDatabaseService.setChatHistoryCallback((ChatHistoryCallback) this);
        messagesDatabaseService.fetchChatHistory(currentUserId,friendId);
        // 加载完成后，隐藏下拉刷新进度条
        swipeRefreshLayout.setRefreshing(false);
    }
    @SuppressLint("NotifyDataSetChanged")
    public void onChatHistoryLoaded(List<UserMessage> userMessages) {
        // 使用加载的消息更新 RecyclerView 适配器和 RecyclerView
        messagesAdapter.setMessages(userMessages);
        recyclerView.scrollToPosition(userMessages.size() - 1);
        // 如果是第一次加载，滚动到最后一条消息
//        if (isFirstLoad) {
//            recyclerView.scrollToPosition(userMessages.size() - 1);
//            isFirstLoad = false;
//            Log.d("好友聊天界面","加载聊天记录到UI成功！");
//        }
        // 通知适配器进行刷新
        messagesAdapter.notifyDataSetChanged();
    }

//    private void scrollToLastMessage() {
//        int lastMessageIndex = messagesAdapter.getItemCount() - 1;
//        if (lastMessageIndex >= 0) {
//            recyclerView.scrollToPosition(lastMessageIndex);
//        }
//    }

    private void sendMessage(String content, int currentUserId, int friendId) {
        // 创建一个 Message 对象并设置相关属性
        UserMessage userMessage = new UserMessage(TimestampUtil.getCurrentMicrosecondTimestamp(),
                currentUserId, friendId,content,LocalDateTime.now());
        // 创建 MessagesService 实例
        MessagesDatabaseService messagesDatabaseService = new MessagesDatabaseService();
        // 调用 saveMessage() 方法保存消息
        messagesDatabaseService.sendMessage(userMessage);
    }

    @SuppressLint("NotifyDataSetChanged")
    private void displayNewMessage(String messageText) {
        // 更新 RecyclerView 的数据源
        messagesAdapter.addMessage(messageText);
        // 通知适配器进行刷新
        messagesAdapter.notifyDataSetChanged();
        // 滚动 RecyclerView 到最后一条消息
        recyclerView.scrollToPosition(messagesAdapter.getItemCount() - 1);
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_chat);
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
        timer = null;
    }
}